package com.xpf.shardingtabledemo.shardingdtable.strategy.DayShardingStrategy;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @auther xpf
 * @date 2023/9/8 10:15
 * @description 按天分表策略返回表名
 *
 *  分成 3、6、10、15、每天(1)
 *  一、假设 当颗粒度为3时，分为
 *   1 -10  table_01
 *   11-20  table_02
 *   21以后 table_03
 *
 * 二、假设颗粒度为6时，分为
 *  1-5      table_01
 *  6-10     table_02
 *  11-15    table_03
 *  16-20    table_04
 *  21-25    table_05
 *  26以后    table_06
 *
 *  以此类推
 *
 */
public class DayShardingStrategy{

    public static String getActualTableName(String originalTableName, int tableNum) {
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        DateTimeFormatter mm = DateTimeFormatter.ofPattern("MM");
        String formattedMonth = now.format(mm);
        DateTimeFormatter dd = DateTimeFormatter.ofPattern("dd");
        String formattedDay  = now.format(dd);
        Integer currentDayInt = Integer.valueOf(formattedDay);

        if (tableNum == 1){
            return originalTableName + "_" + year + "_" + formattedMonth + "_" +formattedDay;
        }

        if ( !(tableNum == 3 || tableNum == 6 || tableNum == 10 || tableNum == 15 )){
            throw new RuntimeException("目前按天分表支持的颗粒度为：3、6、10、15、1（每天），而您输入的颗粒度为" + tableNum );
        }
        int everyNum = 30 / tableNum;
        if ( currentDayInt >= (everyNum * (tableNum - 1) + 1) ){
            return originalTableName + "_" + year + "_" + formattedMonth + "_" + getCompleteTens(tableNum);
        }
        for (int i = 0; i < tableNum; i++) {
            if ( (everyNum * i + 1) <= currentDayInt && currentDayInt <= (everyNum * (i+1)) ){
                return originalTableName + "_" + year + "_" + formattedMonth + "_" + getCompleteTens(i+1);
            }
        }

        return null;
    }

    private static String getCompleteTens(int singleFigure){
        if (0 <= singleFigure && singleFigure<= 9) return "0" + singleFigure;
        return String.valueOf(singleFigure);
    }

    public static void main(String[] args) {
        String mytable = DayShardingStrategy.getActualTableName("mytable", 3);
        System.out.println(mytable);
    }

}
